package com.blue.jdbc.config;

import com.blue.jdbc.datasource.RouteDataSource;
import com.blue.jdbc.dialect.MySQLDialect;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSimpleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.util.Map;

/**
 * RouteDataSource解析
 *
 * @author Jin Zheng
 * @date 2018-10-31
 */
public class RouteDataSourceParser extends AbstractSimpleBeanDefinitionParser
{
	public RouteDataSourceParser()
	{
	}

	@Override
	protected Class<?> getBeanClass(Element element)
	{
		return RouteDataSource.class;
	}

	@Override
	protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder)
	{
		try
		{
			NodeList pkgList = element.getElementsByTagNameNS("http://www.blue.com/schema/jdbc", "target-data-sources");
			if (pkgList.getLength() > 0)
			{
				Element node = (Element) pkgList.item(0).getChildNodes().item(1);
				Map<Object, Object> map = parserContext.getDelegate().parseMapElement(node, builder.getRawBeanDefinition());
				builder.addPropertyValue("targetDataSources", map);
			}

			String defaultDataSource = element.getAttribute("default-data-source");
			builder.addPropertyValue("defaultDataSource", new RuntimeBeanReference(defaultDataSource));
		}
		catch (Exception e)
		{
			parserContext.getReaderContext().error(MySQLDialect.class.getName() + " 无法创建", element, null, e);
		}
	}
}
